<?php
    require('common.php');
        
    $db = new Database();
    $user = getUser($db);
    
    // Error check
    if($user['group'] < 1) {
        redirect('index.php');
        exit();
    }
    if(!isset($_GET['id']))
        throw new Exception('Bad request.');
    
    // Check that the block exists
    $result = $db->query('SELECT id FROM '.
        config('DB_PREFIX').'blocks WHERE id='.intval($_GET['id']));
    if(mysqli_num_rows($result) < 1)
        throw new Exception('No such block.');
    
    // Get the question ids
    $result = $db->query('SELECT id '.
        'FROM '.config('DB_PREFIX').'questions '.
        'WHERE block='.intval($_GET['id']));
    if(mysqli_num_rows($result) == 0)
        message( lang('NO_QUESTIONS_IN_BLOCK'), 'index.php', lang('BACK_TO_HOME') );    
    $qids = array();
    while($row = mysqli_fetch_assoc($result))
        $qids[ $row['id'] ] = 0;
    
    // Get the number of answers
    $result = $db->query('SELECT question, COUNT(*) AS cnt '.
        'FROM '.config('DB_PREFIX').'answers '.
        'WHERE user='.intval($user['id']).' '.
        'GROUP BY question');
    while($row = mysqli_fetch_assoc($result))
        if(array_key_exists( $row['question'], $qids))
            $qids[ $row['question'] ] = $row['cnt'];
    
    // Redirect to a random smallest element
    $min_quids = array();
    foreach($qids as $id => $score) 
        if($score == min($qids)) 
            $min_quids[ $id ] = 1;
    redirect('question.php?id='.array_rand($min_quids));
?>